<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/01/09
 * Time: 17:50
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\fac;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\FinanceBank;
use app\common\model\FinanceInvoiceSetting;
use app\common\model\FinancePayment;
use app\common\model\JobApprove;
use app\common\model\JobFlowModule;
use app\common\model\SysAttachment;
use app\common\service\finance\FinanceService;
use app\common\service\system\SystemService;
use app\common\status\BaseStatus;
use think\facade\Validate;

/**
 * 付款单
 * Class PaymentController
 * @package app\admin\controller\fac
 */
class PaymentController extends BaseController
{
    protected $moduleName = 'finance_payment';

    /**
     * 预赋值
     * @date 2021/01/11
     * @author longli
     */
    protected function loadCommon()
    {
        // 税
        $this->assign("tax", \think\facade\Config::get('param.purchase_tax', 0.17));
        $this->assign('status_pass', JobApprove::JOB_STATUS_PASS);
        $this->assign('status_reject', JobApprove::JOB_STATUS_REJECT);
        $this->assign('pay_status_none', FinancePayment::PAY_STATUS_NONE);
    }

    /**
     * 付款单列表
     * @return string
     * @date 2021/01/09
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $sort = "pay_status, payment_id desc ";
            $order = " desc ";
            if($temp = $this->request->post("order")) $order = " $temp ";
            if($temp = $this->request->post('sort')) $sort .= ", $temp $order";
            $payment = FinancePayment::with(['payUser'])->order($sort);
            $this->searchModel($payment, [
                'eq' => ['pay_type', 'pay_status', 'ref_type', 'is_invoice', 'act_account', 'check_status', 'ref_sn'],
                'like' => ['bank_user'],
                'times' => ['biz_date', 'real_date'],
            ]);
            $limit = $this->getPageSize();
            $payment = $payment->paginate($limit);
            $this->assign("list", $payment->getCollection());
            $this->assign("page", $payment->render());
            return $this->fetch("lists");
        }
        $this->assign('sort', [
            'biz_date' => '待付款日期',
            'real_date' => '已付款日期',
            'act_money' => '应该付金额',
            'real_money' => '已付金额',
        ]);
        $this->assign('order', ['asc', 'desc']);
        $this->assign('pay_type', FinancePayment::$PAY_TYPE);
        $this->assign('pay_status', FinancePayment::$PAY_STATUS);
        $this->assign('is_invoice', ['否', '是']);
        $this->assign('ref_type', BaseStatus::$REF_TYPE);
        $this->assign('check_status', JobFlowModule::$CHECK_STATUS);
        $this->assign('banks', FinanceBank::getAll());
        return $this->fetch('index');
    }

    /**
     * 查看付款单详情
     * @return string|void
     * @date 2021/01/11
     * @author longli
     */
    public function info()
    {
        $payId = $this->request->get("payment_id");
        $payment = FinancePayment::get($payId);
        if(empty($payment)) $this->error("付款单不存在");
        $this->assign('payment', $payment);
        $this->assign("attachment_type_invoice", SysAttachment::FILE_TYPE_INVOICE);
        $this->assign("attachment_type_contract", SysAttachment::FILE_TYPE_CONTRACT);
        $this->assign('attachment_type_other', SysAttachment::FILE_TYPE_OTHER);
        $this->assign("pay_info", $this->renderInfo($payment));
        $this->assign("is_show_check", JobFlowModule::isCheckIng($payment)
            && $this->user->hasPermissions('/fac/payment/check')
        );
        $this->assign("is_show_payment",
            in_array($payment->getData('pay_status'), [FinancePayment::PAY_STATUS_NONE, FinancePayment::PAY_STATUS_APPLY, FinancePayment::PAY_STATUS_PART])
            && JobFlowModule::isCheckFinish($payment)
            && $this->user->hasPermissions('/fac/payment/save')
        );
        $this->assignCheck($payId);
        return $this->fetch("info");
    }

    /**
     * 保存付款信息
     * @date 2021/01/12
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'payment_id'  => 'require',
                'pay_type'  => 'require',
                'act_account'  => 'require',
                'service_charge'  => 'require|egt:0',
                'real_money'  => 'require|gt:0',
            ],[
                'payment_id.require' => '非法请求',
                'pay_type.require' => '付款方式必选',
                'act_account.require' => '付款账号必选',
                'service_charge.require' => '手续费必填',
                'service_charge.egt' => '手续费必需大于等于0',
                'real_money.require' => '付款金额必填',
                'real_money.gt' => '付款金额必需大于0',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
            if(!JobFlowModule::isCheckFinish(FinancePayment::get($data['payment_id']))) return "付款单未审批通过，不能付款";
            if($data['act_money'] + $data['service_charge'] != $data['real_money']) $this->error("付款金额错误");
            $pType = FinancePayment::where('payment_id', $data['payment_id'])->value('pay_type');
            if(in_array($pType, [FinancePayment::PAY_TYPE_BEFORE, FinancePayment::PAY_TYPE_CREDIT, FinancePayment::PAY_TYPE_AFTER]))
                unset($data['pay_type']);
            $data += [
                'pay_status' => FinancePayment::PAY_STATUS_ALL,
                'real_date' => Tools::now(),
                'pay_user_id' => $this->user->id,
            ];
            FinanceService::getInstance()->addPayment($data)
                ? $this->success("添加付款成功")
                : $this->error("添加付款失败");
        }
        // 展示添加付款单
        $payId = $this->request->get("payment_id");
        $payment = FinancePayment::get($payId);
        if(empty($payment)) $this->error("付款单不存在");
        $this->assign('payment', $payment);
        $this->assign('pay_type', FinancePayment::$PAY_TYPE);
        $this->assign("banks", FinanceBank::getAll());
        $this->assign("invoices", FinanceInvoiceSetting::getAll());
        return $this->fetch('save_payment');
    }

    /**
     * 上传附件
     * @date 2021/01/12
     * @author longli
     */
    public function upload()
    {
        $validate = Validate::make([
            'payment_id'  => 'require',
            'type'  => 'require',
            'path'  => 'require',
        ],[
            'payment_id.require' => '非法请求',
            'type.require' => '类型必传',
            'path.require' => '文件路径必传',
        ]);
        $data = $this->request->post();
        if(!$validate->batch()->check($data))
            $this->error(join(', ', $validate->getError()));
        $rootPath = FinanceService::getRootPath($data['path']);
        if(!is_file($rootPath)) $this->error("上传失败");
        if(SysAttachment::hasFile($rootPath)) $this->success("上传成功");
        $data += [
            'md5_code' => md5_file($rootPath),
            'id_type' => FinancePayment::getTable(),
            'ref_id' => $data['payment_id'],
        ];
        SystemService::getInstance()->addAttachment($data)
            ? $this->success("上传成功")
            : $this->error("上传失败");
    }

    /**
     * 渲染自定义付款详情模板
     * @param FinancePayment $payment 付款或者收款数据模型
     * @return string|void
     * @date 2021/01/11
     * @author longli
     */
    private function renderInfo($payment)
    {
        if(empty($payment->ref_sn)) return;
        $classes = '\\app\\common\\model\\' . ucfirst(Tools::toCamelCase($payment->ref_id_type));
        return $this->renderTerp($classes, $payment->ref_sn, "pur/purchase/info/{$payment->getData('ref_type')}");
    }
}